import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:web_admin/views/product/product_form.dart';
import 'package:web_admin/views/product/product_model.dart';
import '../../core/base/base_view_model.dart';
import 'product_list_view_model.dart';

class ProductListView extends StatelessWidget {
  const ProductListView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => ProductListViewModel(),
      child: const _ProductListViewContent(),
    );
  }
}

class _ProductListViewContent extends StatefulWidget {
  const _ProductListViewContent({Key? key}) : super(key: key);

  @override
  _ProductListViewContentState createState() => _ProductListViewContentState();
}

class _ProductListViewContentState extends State<_ProductListViewContent> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      context.read<ProductListViewModel>().fetchProducts();
    });
  }

  void _showProductForm(BuildContext context, {ProductModel? product}) {
    final viewModel = context.read<ProductListViewModel>();
    showDialog(
      context: context,
      builder: (dialogContext) => Dialog(
        child: Container(
          width: 600,
          padding: const EdgeInsets.all(16),
          child: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  product == null ? '添加商品' : '编辑商品',
                  style: Theme.of(dialogContext).textTheme.headlineSmall,
                ),
                const SizedBox(height: 16),
                ProductForm(
                  product: product,
                  onSubmit: (data) async {
                    try {
                      if (product == null) {
                        await viewModel.createProduct(data);
                      } else {
                        await viewModel.updateProduct(product.id, data);
                      }
                      if (dialogContext.mounted) {
                        Navigator.of(dialogContext).pop();
                        ScaffoldMessenger.of(context).showSnackBar(
                          const SnackBar(content: Text('操作成功')),
                        );
                      }
                    } catch (e) {
                      if (dialogContext.mounted) {
                        ScaffoldMessenger.of(context).showSnackBar(
                          SnackBar(content: Text('操作失败：${e.toString()}')),
                        );
                      }
                    }
                  },
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('商品管理'),
        actions: [
          ElevatedButton.icon(
            icon: const Icon(Icons.add),
            label: const Text('新增商品'),
            onPressed: () => _showProductForm(context),
            style: ElevatedButton.styleFrom(
              foregroundColor: Colors.white,
              backgroundColor: Theme.of(context).primaryColor,
            ),
          ),
          const SizedBox(width: 16),
        ],
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Row(
                  children: [
                    Expanded(
                      child: TextField(
                        decoration: const InputDecoration(
                          hintText: '搜索商品...',
                          prefixIcon: Icon(Icons.search),
                          border: OutlineInputBorder(),
                        ),
                        onChanged: (value) => context
                            .read<ProductListViewModel>()
                            .searchProducts(value),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),
            Expanded(
              child: Consumer<ProductListViewModel>(
                builder: (context, viewModel, _) {
                  if (viewModel.isBusy && viewModel.products.isEmpty) {
                    return const Center(child: CircularProgressIndicator());
                  }

                  if (viewModel.state == ViewState.error && viewModel.products.isEmpty) {
                    return Center(
                      child: Text(
                        viewModel.errorMessage ?? '加载失败',
                        style: const TextStyle(color: Colors.red),
                      ),
                    );
                  }

                  final products = viewModel.filteredProducts;
                  if (products.isEmpty) {
                    return const Center(child: Text('暂无商品数据'));
                  }

                  return ListView.builder(
                    itemCount: products.length + (viewModel.hasMore ? 1 : 0),
                    itemBuilder: (context, index) {
                      if (index == products.length) {
                        if (viewModel.isBusy) {
                          return const Center(
                            child: Padding(
                              padding: EdgeInsets.all(16.0),
                              child: CircularProgressIndicator(),
                            ),
                          );
                        } else {
                          WidgetsBinding.instance.addPostFrameCallback((_) {
                            viewModel.fetchProducts(refresh: false);
                          });
                          return const Center(
                            child: Padding(
                              padding: EdgeInsets.all(16.0),
                              child: CircularProgressIndicator(),
                            ),
                          );
                        }
                      }
                      final product = products[index];
                      return Card(
                        margin: const EdgeInsets.only(bottom: 8),
                        child: ListTile(
                          title: Text(product.name),
                          subtitle: Text(
                            '价格: ¥${product.price.toStringAsFixed(2)} | 库存: ${product.stock}',
                          ),
                          trailing: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              IconButton(
                                icon: const Icon(Icons.edit),
                                onPressed: () =>
                                    _showProductForm(context, product: product),
                              ),
                              IconButton(
                                icon: const Icon(Icons.delete),
                                onPressed: () {
                                  showDialog(
                                    context: context,
                                    builder: (context) => AlertDialog(
                                      title: const Text('确认删除'),
                                      content: const Text('确定要删除这个商品吗？'),
                                      actions: [
                                        TextButton(
                                          onPressed: () =>
                                              Navigator.of(context).pop(),
                                          child: const Text('取消'),
                                        ),
                                        TextButton(
                                          onPressed: () {
                                            viewModel.deleteProduct(product.id);
                                            Navigator.of(context).pop();
                                          },
                                          child: const Text(
                                            '删除',
                                            style: TextStyle(color: Colors.red),
                                          ),
                                        ),
                                      ],
                                    ),
                                  );
                                },
                              ),
                            ],
                          ),
                        ),
                      );
                    },
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}